package com.example.shopdemo.service;

import com.example.shopdemo.dto.ProductExecution;
import com.example.shopdemo.entity.Product;
import com.example.shopdemo.entity.ProductImg;
import com.example.shopdemo.enums.ProductStateEnum;
import com.example.shopdemo.repository.ProductImgRepository;
import com.example.shopdemo.repository.ProductRepository;
import com.example.shopdemo.utils.FileUtil;
import com.example.shopdemo.utils.ImageUtil;
import com.example.shopdemo.utils.SpecificationsBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-01-21
 **/
@Service
public class ProductServiceImpl {

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private ProductImgRepository productImgRepository;


    public List<Product> getProductListByProductCategoryId(Long productCategoryId){
        return productRepository.findByProductCategoryId(productCategoryId);
    }

    public void updateProductCategoryToNull(Long productCategoryId){
        productRepository.updateProductCategoryToNull(productCategoryId);
    }

    public ProductExecution addProduct(Product product, MultipartFile imgAddr, List<MultipartFile> productImgList){
        if(product!=null &&product.getShopId()!=null){
            Set<ProductImg> productImgSet = new HashSet<>();
            product.setCreateTime(new Date());
            product.setLastEditTime(new Date());
            product.setEnableStatus(1);
            if(imgAddr!=null){
                addImgAddr(product,imgAddr);
            }
            if(productImgList!=null&&productImgList.size()>0){
                productImgSet = addProductImg(product,productImgList);
            }
            product.setProductImgList(productImgSet);
            Product productResult = productRepository.save(product);
            return new ProductExecution(ProductStateEnum.SUCCESS,productResult);
        }else{
            return new ProductExecution(ProductStateEnum.EMPTY);
        }

    }

    public Set<ProductImg> addProductImg(Product product, List<MultipartFile> productImgList){
        Set<ProductImg> productImgSet = new HashSet<>();
        String dest = FileUtil.getShopImagePath(product.getShopId());
        List<String> productImgAddrList = ImageUtil.generateNormalImgs(productImgList,dest);
        if(productImgAddrList!=null&&productImgAddrList.size()>0){
            for(String productImgAddr : productImgAddrList) {
                ProductImg productImg = new ProductImg();
                productImg.setImgAddr(productImgAddr);
                productImg.setCreateTime(new Date());
                ProductImg productImgResult = productImgRepository.save(productImg);
                if(productImgResult==null){
                    throw new RuntimeException("创建商品详情图片失败");
                }
                productImgSet.add(productImg);
            }
        }
        return productImgSet;
    }

    public void addImgAddr(Product product,MultipartFile imgAddr){
        String dest = FileUtil.getShopImagePath(product.getShopId());
        String imgAddrResult = ImageUtil.generateThumbnail(imgAddr,dest);
        product.setImgAddr(imgAddrResult);
    }


    public Product getProductById(Long productId){
        return productRepository.findOne(productId);
    }

    public ProductExecution modifyProduct(Product product, MultipartFile imgAddr, List<MultipartFile> productImgList){
        if(product.getShopId()!=null){
          Product  tempProduct = productRepository.findOne(product.getProductId());
            tempProduct.setLastEditTime(new Date());
            if(imgAddr!=null){
                if(tempProduct.getImgAddr()!=null){
                    FileUtil.deleteFile(product.getImgAddr());
                }
                addImgAddr(tempProduct,imgAddr);
            }
            if(productImgList!=null&&productImgList.size()>0){
                deleteProductImgs(tempProduct);
                addProductImg(tempProduct,productImgList);
            }

            tempProduct.setProductName(product.getProductName());
            tempProduct.setProductDesc(product.getProductDesc());
            tempProduct.setNormalPrice(product.getNormalPrice());
            tempProduct.setPromotionPrice(product.getPromotionPrice());
            tempProduct.setPriority(product.getPriority());
            tempProduct.setProductCategoryId(product.getProductCategoryId());
            Product productResult = productRepository.save(tempProduct);
            if(productResult!=null){
                return new ProductExecution(ProductStateEnum.SUCCESS,productResult);
            }else{
                return new ProductExecution(ProductStateEnum.INNER_ERROR);
            }
        }else{
            return new ProductExecution(ProductStateEnum.EMPTY);
        }
    }

    private void deleteProductImgs(Product tempProduct){
        Set<ProductImg> productImgSet = tempProduct.getProductImgList();
        for(ProductImg productImg:productImgSet){
            FileUtil.deleteFile(productImg.getImgAddr());
            productImgRepository.deleteByProductImgId(productImg.getProductImgId());
        }
    }

    public ProductExecution getProductList(Product productCondition,int page,int size){
        String productName = productCondition.getProductName();
        String enableStatus = String.valueOf(productCondition.getEnableStatus());
        String productCategoryId = String.valueOf(productCondition.getProductCategoryId());
        String shopId = String.valueOf(productCondition.getShopId());

        SpecificationsBuilder<Product> specificationsBuilder = new SpecificationsBuilder<>();
        if(!(StringUtils.isEmpty(shopId)|| "null".equals(shopId))){
            specificationsBuilder.with("shopId","=",shopId);
        }
        if(!(StringUtils.isEmpty(productName)||"null".equals(productName))){
            specificationsBuilder.with("productName","=",productName);
        }
        if(!(StringUtils.isEmpty(productCategoryId)||"null".equals(productCategoryId))){
            specificationsBuilder.with("productCategoryId","=",productCategoryId);
        }
        if(!(StringUtils.isEmpty(enableStatus)||"null".equals(enableStatus))){
            specificationsBuilder.with("enableStatus","=",enableStatus);
        }
        Specification<Product> spec = specificationsBuilder.build();

        Pageable pageable = new PageRequest(page,size,new Sort(new Sort.Order(Sort.Direction.DESC,"priority")));
        Page<Product> productPage = productRepository.findAll(spec,pageable);
        ProductExecution se = new ProductExecution();
        if(productPage.getContent()!=null){
            se.setProductList(productPage.getContent());
            se.setCount(new Long(productPage.getTotalElements()).intValue());
        }else{
            se.setState(ProductStateEnum.INNER_ERROR.getKey());
        }
        return se;
    }


}


